import ResizeObserver from 'resize-observer-polyfill'

const syncVar = (node, binding, vnode) => {
  if (!binding.arg) return
  if (typeof binding.value !== 'boolean') {
    binding.value[binding.arg] = node.offsetWidth < node.scrollWidth
  } else {
    vnode.ctx.devtoolsRawSetupState[binding.arg].value = node.offsetWidth < node.scrollWidth
  }
}

const Trunced = {
  mounted(el, binding, vnode) {
    const node = binding.modifiers.parent ? el.parentNode : el
    syncVar(node, binding, vnode)

    const ro = new ResizeObserver(entries => {
      entries[0].target && syncVar(node, binding, vnode)
    })
    ro.observe(node)
  },
  updated(el, binding, vnode) {
    const node = binding.modifiers.parent ? el.parentNode : el
    syncVar(node, binding, vnode)
  }
}

/**
 * 实时检测是否出现省略号
 * 用法：
 * v-trunced:value="value" 基本数据类型的形式
 * v-trunced:key="obj" 对象类型的形式
 * v-trunced:key.parent="obj" 插槽检测父元素可以使用
 */

export default Trunced
